/*
 * @(#)ListWorkflowTaskAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.RedirectingActionForward;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.user.dao.UserDelegationDAObject;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;

/**
 * <p>Class Name:       ListWorkflowTaskAction.java    </p>
 * <p>Description:      The list action class for ListWorkflowTask.jsp</p>
 * @author           Angus Shiu
 * @company          DCIVision Limited
 * @creation date    11/12/2003
 * @version          $Revision: 1.22.2.1 $
 */

public class ListWorkflowTaskAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.22.2.1 $";

  /** Creates a new instance of ListWorkflowTaskAction */
  public ListWorkflowTaskAction() {
    super();
    this.setListName("workflowTaskList");
    // this.setListFunctionName("getListPendingForUser");
    this.setListFunctionName("getPendingList4UserCanRead");
  }

  public String getFunctionCode() {
    return(SystemFunctionConstant.WORKFLOW_TASK);
  }

  public String getMajorDAOClassName() {
    return("com.dcivision.workflow.dao.WorkflowProgressDAObject");
  }

  /**
   * setPageTitle
   * set the extend page title and page path.
   * default page path/title will be created by navmode and functionCode
   */
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping, ActionForward actionForward){
    ListWorkflowProgressForm listWorkflowProgressForm = (ListWorkflowProgressForm)form;
    String extendTitle="";

    boolean isShowProcessedList = GlobalConstant.TRUE.equals(listWorkflowProgressForm.getShowProcessedList());

    if(isShowProcessedList){
      extendTitle = MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(), "workflow.label.processed_list");
    }else{
      extendTitle = MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(), "workflow.label.pending_list");
    }
    request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE, extendTitle);
    request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE_SHOW_ONLY, new Boolean(true));
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    // Added by Lun
    // If the request is from "Receive Paper Document", don't display the list at the beginning
    // TODO: check if paper document module is enabled
	   String list=request.getParameter("list");
	  if (!Utility.isEmpty(list)){ 
		  if (!((ListWorkflowProgressForm)form).getShowProcessedList().equals(request.getParameter("list"))){
			  ((ListWorkflowProgressForm)form).setShowProcessedList(request.getParameter("list"));
		  }
		  //sliever.hu.add	
	  }
    if ( mapping.getPath().equals("/workflow/ListWorkflowRecvPaperDoc") &&
          ( ((ListWorkflowProgressForm) form).getDocReferenceNumber() == null ||
            ((ListWorkflowProgressForm) form).getDocReferenceNumber().equals("") )
        ) {
      request.setAttribute ( this.m_sListName, new ArrayList() );
      return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    } else {
     log.debug ( "DocRefNumber="+((ListWorkflowProgressForm) form).getDocReferenceNumber() );
    }
    // End by Lun

    UserDelegationDAObject delegationDAO = (UserDelegationDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.UserDelegationDAObject");
    List delegationList = delegationDAO.getListDelegatedToUser();
    WorkflowProgressDAObject progressDAO = new WorkflowProgressDAObject(this.getSessionContainer(request), this.getConnection(request));
    
    //Add by Samlin 
    progressDAO.setPendingUserListCount(delegationList);
    // And by Samlin
    
    request.setAttribute("delegationList", delegationList);

    ListWorkflowProgressForm listForm = (ListWorkflowProgressForm) form;
    if (form != null && GlobalConstant.OP_MODE_LIST_RETAIN.equals(((AbstractSearchForm)form).getOpMode())) {
      // Retain the attributes of search form.
      if ((ActionForm)request.getSession().getAttribute(this.m_sListName)!=null) {
        form = (ActionForm)request.getSession().getAttribute(this.m_sListName);
        request.setAttribute(mapping.getAttribute(), form);
      } else {
        request.getSession().setAttribute(this.m_sListName, form);
      }
    } else {
      // Set the search from into session for remembering the settings.
      request.getSession().setAttribute(this.m_sListName, form);
    }

    log.info(this.getClass().getName()+", OP Mode:"+listForm.getOpMode()+", Nav Mode:"+listForm.getNavMode());

    // Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }
    
    if ( "L".equals(((AbstractSearchForm)form).getOpMode())) {
      // Retain the attributes of search form.
      if ((ActionForm)request.getSession().getAttribute(this.m_sListName)!=null) {
        listForm = (ListWorkflowProgressForm)request.getSession().getAttribute(this.m_sListName);  
      }
    }      
    //Sliever.hu.add
    if (!GlobalConstant.OP_MODE_LIST_DELETE.equals(listForm.getOpMode()) && GlobalConstant.TRUE.equals(listForm.getShowProcessedList())) { 
      try {
    	  if(GlobalConstant.NOT_AVAILABLE.equals(listForm.getSortAttribute())){
    		  listForm.setSortAttribute("PROGRESS_PRIORITY");
    	  }
        List resultList = progressDAO.getListProcessedForUser(listForm);
        request.setAttribute(this.m_sListName, resultList);
      } catch (ApplicationException e) {
        this.handleApplicationException(request, e);
        request.setAttribute(this.m_sListName, new ArrayList());
      }
      return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    } else {
      String searchField = ((AbstractSearchForm)form).getBasicSearchField();
      String searchKey = ((AbstractSearchForm)form).getBasicSearchKeyword();
      if(!Utility.isEmpty(searchField)
          &&searchField.trim().equalsIgnoreCase("WP.TRACK_ID")
          &&!Utility.isEmpty(searchKey)
          &&searchKey.startsWith("0")){
        
        try {
          ((AbstractSearchForm)form).setBasicSearchKeyword(Integer.valueOf(searchKey).toString());
        }
        catch (Exception e) {
          log.error(e.toString());
        }
        
      }
      ActionForward actionForward = super.execute ( mapping, form, request, response );
      List resultList = (List)request.getAttribute(this.m_sListName);

      // Added by Lun
      // User search a paper document:
      // - If only 1 record found, and if the task is not completed, go directly to the process page.
      // - Otherwise show the list with the progress icon enabled.
log.debug ( "-------------------"+((ListWorkflowProgressForm) form).getCurStartRowNo() );
      if ( resultList.size() == 1 && mapping.getPath().equals("/workflow/ListWorkflowRecvPaperDoc") && "1".equals(((ListWorkflowProgressForm) form).getCurStartRowNo()) ) {
        WorkflowProgress workflowProgress = (WorkflowProgress)((List)request.getAttribute(this.m_sListName)).toArray()[0];
        boolean bProgressFinished = !(WorkflowProgress.STATUS_PENDING.equals((workflowProgress).getStatus())||WorkflowProgress.STATUS_IN_PROGRESS.equals((workflowProgress).getStatus()));
        String navMode = GlobalConstant.NAV_MODE_VIEW;
        if ( !bProgressFinished ) {
          navMode = GlobalConstant.NAV_MODE_EDIT;
        }
        actionForward = new RedirectingActionForward ( "MaintWorkflowTask.do?navMode="+navMode+"&trackID="+workflowProgress.getTrackID()+"&ID="+workflowProgress.getID()+"&workflowRecordID="+workflowProgress.getWorkflowRecordID() );
      }
      // End by Lun

      return actionForward;
    }
  }
}